import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { connect } from 'dva';
import moment from 'moment';
import { getToken } from '../../../components/common/PateoForm/utils/helper';
import { Modal, Badge, Card, message, Table, Row, Col, Button, Popconfirm } from 'antd';
import * as G from '../../../utils/common';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  commercialVehicleTaskCenter: state.commercialVehicleTaskCenter,
  loading: state.loading.models['commercialVehicleTaskCenter'],
});
class TaskCenter extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      statusData: [
        { value: 'Pending', label: '待处理' },
        { value: 'Processing', label: '处理中' },
        { value: 'Success', label: '处理成功' },
        { value: 'Fail', label: '处理失败' },
      ],
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, dispatch } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      //  打开弹窗
      const { formValues } = this.state;
      const tempParam = {
        ...formValues,
        pageNo: 1,
        pageSize: 10,
      };
      dispatch({
        type: 'commercialVehicleTaskCenter/postFetchPageParamAndBody',
        payload: { url: '/commodity/vehicle/monitor/taskRecord/page', ...tempParam },
      });
    }
  }

  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      const [start, end] = fields.handleTimeRange;
      fields['startTime'] = moment(start).format('YYYY-MM-DD HH:mm:ss');
      fields['endTime'] = moment(end).format('YYYY-MM-DD HH:mm:ss');
      delete fields['handleTimeRange'];
      /* if (moment(fields.startTime).isBefore(moment(fields.endTime).subtract(1, 'months'))) {
        message.warning('操作时间区间为一个月！');
        return false;
      } else {
        return fields;
      } */
    }
    return fields;
  };

  handleFormReset = () => {
    this.setState({
      formValues: {},
    });
  };

  close = () => {
    const { closeModal } = this.props;
    closeModal();
  };

  getStatusTxt = (str: string) => {
    const { statusData } = this.state;
    let txt = '';
    statusData.some((item: any) => {
      let state = str === item.value;
      if (state) {
        txt = item.label;
      }
      return state;
    });
    return txt;
  };

  handleDownloadLog = (record: any) => {
    const { dispatch } = this.props;
    const { operator, vin } = JSON.parse(record.request);
    // this.setState({ exportLoading: true })
    dispatch({
      type: 'http/postDataWithRes',
      payload: {
        url: '/commodity/vehicle/monitor/operateRecord/export',
        vin: vin,
        operator: operator,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('操作成功');
          this.handleFresh();
        }
        // this.setState({ exportLoading: false })
      },
    });
  };

  handleFresh = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      pageNo: 1,
      pageSize: 10,
    };
    dispatch({
      type: 'commercialVehicleTaskCenter/postFetchPageParamAndBody',
      payload: { url: '/commodity/vehicle/monitor/taskRecord/page', ...tempParam },
    });
  };

  render() {
    const { modalVisible } = this.props;
    const {
      commercialVehicleTaskCenter: {
        pageData: { rows, pagination, total },
      },
      loading,
      dispatch,
    } = this.props;
    // let pathname = '/commercialVehicleMonitor/taskCenter'
    const { formValues, statusData } = this.state;

    const columns = [
      {
        title: '任务名称',
        dataIndex: 'taskName',
      },
      {
        title: '任务时间',
        dataIndex: 'taskTime',
      },
      {
        title: '任务状态',
        dataIndex: 'status',
        render: (text: any, record: any) => {
          return this.getStatusTxt(text);
        },
      },
      {
        title: '创建人',
        dataIndex: 'operator',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作',
        dataIndex: 'opt',
        fixed: 'right',
        render: (text: any, record: any) => {
          // 按钮的样式
          const btnProps = {
            size: 'small',
            ghost: true,
            type: 'primary',
            // style: { marginLeft: 12 },
          };
          let btns = [];
          if (record.status === 'Success') {
            btns.push(
              <Button
                key={'btn'}
                href={record.url}
                // onClick={() => {}}
                {...btnProps}
                // disabled={item.disabled || false}
              >
                下载文件
              </Button>,
            );
          }
          if (record.status === 'Fail') {
            btns.push(
              <Button
                key={'btn'}
                onClick={() => {
                  this.handleDownloadLog(record);
                }}
                {...btnProps}
              >
                重新导出
              </Button>,
            );
          }
          return btns;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      total,
      showTotal: () => <span>共&nbsp;{total}&nbsp;条</span>,
    };

    const tableProps = {
      columns,
      // rowKey: (record: any) => record.id,
      dataSource: rows,
      loading,
      pagination: paginationProps,
      // rowSelection,
      // selectedRowKeys,
      scroll: { x: 'max-content' },
    };

    const searchItems = [
      {
        title: '任务名称',
        type: 'input',
        key: 'taskName',
      },
      {
        title: '任务状态',
        type: 'select',
        // customStyle: 6,
        selectOptions: statusData,
        key: 'taskStatus',
      },
      {
        title: '任务时间',
        type: 'rangePicker',
        customStyle: 12,
        key: 'handleTimeRange',
      },
    ];

    return (
      <Modal
        title="任务中心"
        // style={{ width: '800px' }}
        width={900}
        bodyStyle={{ maxHeight: '700px' }}
        footer={null}
        visible={modalVisible}
        onCancel={this.close}
      >
        <PateoSearchForm
          onRef={(val: any) => (this.searchForm = val)}
          searchItems={searchItems}
          fetchParams={{
            type: 'commercialVehicleTaskCenter/postFetchPageParamAndBody',
            url: '/commodity/vehicle/monitor/taskRecord/page',
          }}
          extraArgs={{ pageNo: 1, pageSize: 10 }}
          saveFormValues={(val: any) =>
            this.setState({
              formValues: Object.assign(formValues, val),
            })
          }
          handleFormReset={this.handleFormReset}
          handleFieldsValue={this.dataFormat}
        />
        <div className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'commercialVehicleTaskCenter/postFetchPageParamAndBody',
              url: '/commodity/vehicle/monitor/taskRecord/page',
              extraArgs: {},
            }}
            formValues={formValues}
            currentName="pageNo"
            pageSizeName="pageSize"
          />
        </div>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(TaskCenter);
